package com.ruoyi.web.controller.finance;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.finance.domain.*;
import com.ruoyi.finance.domain.DTO.KltPurchaseDetailDTO;
import com.ruoyi.finance.domain.DTO.KltPurchaseDetailStockDTO;
import com.ruoyi.finance.domain.VO.StockVO;
import com.ruoyi.finance.service.KltPurchaseBatchService;
import com.ruoyi.finance.service.KltPurchaseDetailService;
import com.ruoyi.finance.service.KltStockService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * (KltPurchaseDetail)表控制层
 *
 * @author makejava
 * @since 2024-12-19 12:18:03
 */
@RestController
@RequestMapping("finance/kltPurchaseDetail")
public class KltPurchaseDetailController extends BaseController {
    /**
     * 服务对象
     */
    @Resource
    private KltPurchaseDetailService kltPurchaseDetailService;
    @Resource
    private KltPurchaseBatchService kltPurchaseBatchService;
    @Resource
    private KltStockService kltStockService;
    /**
     * 分页查询所有数据
     *
     * @param page 分页对象
     * @param kltPurchaseDetail 查询实体
     * @return 所有数据
     */
    @GetMapping("/list")
    public TableDataInfo selectAll( KltPurchaseDetailStockDTO kltPurchaseDetail) {
        startPage();
        List<KltPurchaseDetailStockDTO> list = kltPurchaseDetailService.getAllKltPurchaseDetailStockList(kltPurchaseDetail);
        return getDataTable(list);

    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public AjaxResult selectOne(@PathVariable Serializable id) {
        return success(this.kltPurchaseDetailService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param kltPurchaseDetail 实体对象
     * @return 新增结果
     */
    @PostMapping
    public AjaxResult insert(@RequestBody KltPurchaseDetail kltPurchaseDetail) {
        return success(this.kltPurchaseDetailService.save(kltPurchaseDetail));
    }

    /**
     * 修改数据
     *
     * @param kltPurchaseDetail 实体对象
     * @return 修改结果
     */
    @PutMapping
    public AjaxResult update(@RequestBody KltPurchaseDetail kltPurchaseDetail) {
        return success(this.kltPurchaseDetailService.updateById(kltPurchaseDetail));
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @DeleteMapping
    public AjaxResult delete(@RequestParam("idList") List<Long> idList) {
        return success(this.kltPurchaseDetailService.purchaseDetailDeleteStock(idList));
    }


    @GetMapping("count")
    public AjaxResult count( KltPurchaseDetail kltPurchaseDetail) {
        long count = this.kltPurchaseDetailService.count(new QueryWrapper<>(kltPurchaseDetail));
        return success(count);
    }

    @Transactional
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<KltPurchaseDetailDTO> util = new ExcelUtil<KltPurchaseDetailDTO>(KltPurchaseDetailDTO.class);
        List<KltPurchaseDetailDTO> KltPurchaseDetailDTO = util.importExcel(file.getInputStream());
        String operName = getUsername();

        List<KltPurchaseDetail> KltPurchaseDetailList = new ArrayList<>();
        for (KltPurchaseDetailDTO PurchaseDetail : KltPurchaseDetailDTO) {
//        找到批次id 或新增
            KltPurchaseBatch kltPurchaseBatch1 = new KltPurchaseBatch();
            KltStock kltStock = new KltStock();
            KltPurchaseDetail kltPurchaseDetail = new KltPurchaseDetail();


            kltPurchaseBatch1.setPurchaser(PurchaseDetail.getPurchaser());
            kltPurchaseBatch1.setPurchaseDate(PurchaseDetail.getPurchaseDate());
            kltPurchaseBatch1.setOrderName(PurchaseDetail.getOrderName());
            kltPurchaseBatch1.setOrderNumber(PurchaseDetail.getOrderNumber());
            Page<KltPurchaseBatch> page = new Page<KltPurchaseBatch>(1,10000);
            Page<KltPurchaseBatch> count = kltPurchaseBatchService.page(page, new QueryWrapper<>(kltPurchaseBatch1));
            if(count.getRecords().isEmpty()){
                kltPurchaseBatch1.setPurchaseId(kltPurchaseBatchService.getMaxId()+1);
                kltPurchaseBatch1.setCreateSource(operName);
                kltPurchaseBatch1.setUpdateUser(operName);
                try {
                    boolean save = kltPurchaseBatchService.save(kltPurchaseBatch1);
                } catch (Exception e) {
                    throw new RuntimeException("添加批次失败");
                }
            }else {
                kltPurchaseBatch1.setPurchaseId(count.getRecords().get(0).getPurchaseId());
            }

            kltPurchaseDetail.setPurchaseId(kltPurchaseBatch1.getPurchaseId());

            kltStock.setProductName(PurchaseDetail.getProductName());
            kltStock.setModel(PurchaseDetail.getModel());
            kltStock.setUnit(PurchaseDetail.getUnit());

            Page<KltStock> KltStockPage = new Page<KltStock>(1,10000);
            Page<KltStock> KltStockList = kltStockService.page(KltStockPage, new QueryWrapper<>(kltStock));

            if(KltStockList.getRecords().isEmpty()){
                kltStock.setStockQuantity(PurchaseDetail.getStockQuantity());
                kltStock.setStockId(kltStockService.getMaxId()+1);
                kltStock.setCreateSource(operName);
                kltStock.setUpdateUser(operName);
                try {
                    boolean save = kltStockService.save(kltStock);
                } catch (Exception e) {
                    throw new RuntimeException("添加仓库失败");
                }
            }else{
                kltStock.setStockId(KltStockList.getRecords().get(0).getStockId());
                KltStockList.getRecords().get(0).setStockQuantity(KltStockList.getRecords().get(0).getStockQuantity()+PurchaseDetail.getStockQuantity());
                kltStock.setUpdateUser(operName);
                try {
                    boolean save =kltStockService.updateById(KltStockList.getRecords().get(0));
                } catch (Exception e) {
                    throw new RuntimeException("添加仓库失败");
                }
            }
            kltPurchaseDetail.setStockId(kltStock.getStockId());
            kltPurchaseDetail.setUnit (PurchaseDetail.getUnit());
            kltPurchaseDetail.setQuantity  (PurchaseDetail.getQuantity());
            kltPurchaseDetail.setOrderNumberProduct(PurchaseDetail.getOrderNumberProduct());
            kltPurchaseDetail.setUnitPrice(PurchaseDetail.getUnitPrice());
            kltPurchaseDetail.setAmount(PurchaseDetail.getAmount());
            kltPurchaseDetail.setTaxIncludedPrice(PurchaseDetail.getTaxIncludedPrice());
            kltPurchaseDetail.setTotalPrice(PurchaseDetail.getTotalPrice());
            kltPurchaseDetail.setPaymentVoucher(PurchaseDetail.getPaymentVoucher());
            kltPurchaseDetail.setPaymentDate(PurchaseDetail.getPaymentDate());
            kltPurchaseDetail.setPaymentAmount(PurchaseDetail.getPaymentAmount());
            kltPurchaseDetail.setUnpaidAmount (PurchaseDetail.getUnpaidAmount());
            kltPurchaseDetail.setInvoiceNumber(PurchaseDetail.getInvoiceNumber());
            kltPurchaseDetail.setInvoiceQuantity(PurchaseDetail.getInvoiceQuantity());
            kltPurchaseDetail.setInvoiceAmount(PurchaseDetail.getInvoiceAmount());
            kltPurchaseDetail.setUnpaidInvoiceAmount(PurchaseDetail.getUnpaidInvoiceAmount());
            kltPurchaseDetail.setDeliveryDate(PurchaseDetail.getDeliveryDate());
            KltPurchaseDetailList.add(kltPurchaseDetail);
        }


        boolean b = kltPurchaseDetailService.saveBatch(KltPurchaseDetailList);
        String message="";
        if(b){
            message = "导入成功";
        }
        return success(message);
    }
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<KltPurchaseDetailDTO> util = new ExcelUtil<KltPurchaseDetailDTO>(KltPurchaseDetailDTO.class);
        util.importTemplateExcel(response, "采购与库存情况");
    }
    @PostMapping("/export")
    public void export(HttpServletResponse response,  KltPurchaseDetail kltPurchaseBatch)
    {
        List<KltPurchaseDetail> list = kltPurchaseDetailService.getAllKltPurchaseDetail(new QueryWrapper<>(kltPurchaseBatch));
        List<KltPurchaseDetailDTO> list1 = new ArrayList<>();
        list.forEach(KltPurchaseDetail->{
            KltPurchaseDetailDTO kltPurchaseDetailDTO = new KltPurchaseDetailDTO();

            if(KltPurchaseDetail.getPurchaseId()!=null&&KltPurchaseDetail.getPurchaseId()!=0){
                KltPurchaseBatch byId = kltPurchaseBatchService.getById(KltPurchaseDetail.getPurchaseId());
                kltPurchaseDetailDTO.setPurchaser(byId.getPurchaser());
                kltPurchaseDetailDTO.setPurchaseDate(byId.getPurchaseDate());
                kltPurchaseDetailDTO.setOrderNumber(byId.getOrderNumber());
                kltPurchaseDetailDTO.setOrderName(byId.getOrderName());
            }
            if(KltPurchaseDetail.getStockId()!=null){
                KltStock byId1 = kltStockService.getById(KltPurchaseDetail.getStockId());
                kltPurchaseDetailDTO.setProductName(byId1.getProductName());
                kltPurchaseDetailDTO.setModel(byId1.getModel());
                kltPurchaseDetailDTO.setStockQuantity(byId1.getStockQuantity());
                kltPurchaseDetailDTO.setUnit (byId1.getUnit());
            }
            kltPurchaseDetailDTO.setQuantity  (KltPurchaseDetail.getQuantity());
            kltPurchaseDetailDTO.setOrderNumberProduct (KltPurchaseDetail.getOrderNumberProduct());
            kltPurchaseDetailDTO.setUnitPrice(KltPurchaseDetail.getUnitPrice());
            kltPurchaseDetailDTO.setAmount(KltPurchaseDetail.getAmount());
            kltPurchaseDetailDTO.setTaxIncludedPrice(KltPurchaseDetail.getTaxIncludedPrice());
            kltPurchaseDetailDTO.setTotalPrice(KltPurchaseDetail.getTotalPrice());
            kltPurchaseDetailDTO.setPaymentVoucher(KltPurchaseDetail.getPaymentVoucher());
            kltPurchaseDetailDTO.setPaymentDate(KltPurchaseDetail.getPaymentDate());
            kltPurchaseDetailDTO.setPaymentAmount(KltPurchaseDetail.getPaymentAmount());
            kltPurchaseDetailDTO.setUnpaidAmount (KltPurchaseDetail.getUnpaidAmount());
            kltPurchaseDetailDTO.setInvoiceNumber(KltPurchaseDetail.getInvoiceNumber());
            kltPurchaseDetailDTO.setInvoiceQuantity(KltPurchaseDetail.getInvoiceQuantity());
            kltPurchaseDetailDTO.setInvoiceAmount(KltPurchaseDetail.getInvoiceAmount());
            kltPurchaseDetailDTO.setInvoiceDate(KltPurchaseDetail.getInvoiceDate());
            kltPurchaseDetailDTO.setUnpaidInvoiceAmount(KltPurchaseDetail.getUnpaidInvoiceAmount());
            kltPurchaseDetailDTO.setDeliveryDate(KltPurchaseDetail.getDeliveryDate());
            list1.add(kltPurchaseDetailDTO);
        });
        ExcelUtil<KltPurchaseDetailDTO> util = new ExcelUtil<KltPurchaseDetailDTO>(KltPurchaseDetailDTO.class);
        util.exportExcel(response,list1,"采购与库存情况");
    }

    /*
    * 到货加库存
    * */
    @PutMapping("/addStockByPurchase")
    public AjaxResult addStockByPurchase(@RequestBody KltPurchaseDetail kltPurchaseDetail) {
        return success(this.kltPurchaseDetailService.purchaseDetailInsertStock(kltPurchaseDetail));
    }

    /*
     * 整理到货情况
     * */
    @GetMapping("/purchaseDetailArrive")
    public AjaxResult getPurchaseDetailArrive(@RequestBody KltSalesOrder kltSalesOrder) {
        return success(this.kltPurchaseDetailService.purchaseDetailArrive(kltSalesOrder));
    }


    /*
     * 统计采购到货情况
     * */
    @GetMapping("/getProcurementStatistics")
    public AjaxResult getProcurementStatistics(Integer salesOrderId) {
//        整理
        Map<String, Double> procurementStatistics = kltPurchaseDetailService.getProcurementStatistics(salesOrderId);
        return success(procurementStatistics);
    }


}

